package com.example.demo.tool.archery;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.Data;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/24 17:16
 */

@Slf4j
@Data
public class NestResultContainer implements ResultContainer{
    JSONObject originalData;
    List<Map<String, Object>> result;
    String idColumn;
    String parentColumn;
    String tableName;
    JSONArray columns;
    JSONArray data;
    List<Object> params = new ArrayList<>();
    int deepth = 0;
     ResultStrategy resultStrategy  ;
    public NestResultContainer(JSONObject originalData,    String tableName, String idColumn,String parentColumn) {
        columns = originalData.getJSONObject("data").getJSONArray("column_list");
        this.idColumn = idColumn;
        this.parentColumn = parentColumn;
    }

    public NestResultContainer(JSONObject originalData,  String tableName,String idColumn,String parentColumn,ResultStrategy resultStrategy) {
        this(originalData, tableName,idColumn, parentColumn);
        this.resultStrategy = resultStrategy;

    }

    public boolean hasNext() {
        JSONArray rows = originalData.getJSONObject("data").getJSONArray("rows");
        return rows.size() > 0;
    }

    void process(JSONObject originalData) {
        this.originalData = originalData;
        //deepth++;
        JSONArray rows = originalData.getJSONObject("data").getJSONArray("rows");
        rows.forEach(row -> {
            JSONArray data = (JSONArray) row;
            //data.add(deepth);

        });
        if (ObjectUtil.isNull(data)) {
            data = rows;
        } else {
            data.addAll(rows);
        }
        params.clear();
        for (int i = 0; i < rows.size(); i++) {
            int index = getColumnIndex(idColumn);
            JSONArray row = (JSONArray) rows.get(i);
            params.add(row.get(index));
        }
    }

    int getColumnIndex(String columnName) {
        for (int i = 0; i < columns.size(); i++) {
            if (columns.get(i).equals(columnName)) {
                return i;
            }
        }
        return -1;
    }

    public String getDynamicCondition() {
        StringBuilder sb = new StringBuilder();
        if (params.size() > 0) {
            sb.append(" and ").append(parentColumn).append(" in (");
        }
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i));
            if (i != params.size() - 1) {
                sb.append(",");
            }
        }
        if (params.size() > 0) {
            sb.append(" ) ");
        }
        return sb.toString();
    }

    public String getSqlResult() {
        StringBuilder sb = new StringBuilder();
        int index = getColumnIndex(idColumn);
        sb.append("(");
        for (int i = 0; i < data.size(); i++) {
            JSONArray row = (JSONArray) data.get(i);
            sb.append(row.get(index));
            if (i != data.size() - 1) {
                sb.append(",");
            }
        }
        sb.append(")");
        return sb.toString();
    }
    public String getInsertSqlResult() {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into "+tableName+"(");
        if(CollectionUtil.isNotEmpty( columns)){
            for (int i = 0; i < columns.size(); i++) {
                if (i != columns.size() - 1) {
                    sb.append(columns.get(i)).append( ",");
                }else{
                    sb.append(columns.get(i));
                }
            }
        }

        sb.append(") values ");
        for (int i = 0; i < data.size(); i++) {
            sb.append("(");

            JSONArray row = (JSONArray) data.get(i);
            for (int j = 0; j < row.size(); j++) {
                Object value = row.get(j);
//                if(j==5){
//                    sb.append( "JSON_QUOTE(");
//                }
//                if(j==5){
//                    value = value.toString().replace("\\", "\\\\");
//                }
                value = formatWithQuotes(value);
                sb.append(value);
//                if(j==5){
//                    sb.append( ")");
//                }
                if (j != row.size() - 1) {
                    sb.append(",");
                }
            }
            if (i!= data.size() - 1) {
                sb.append("),");
            }else{
                sb.append(");");
            }

        }

        return sb.toString();
    }

    public static String formatWithQuotes(Object obj) {
        if (obj == null) {
            return "null"; // null 通常不加引号
        }

        // 判断实际类型
        if (obj instanceof String) {
            // 字符串：加单引号，并转义内部的单引号（避免冲突）
            String str = (String) obj;
            // 替换字符串中的单引号为 \'（防止闭合）
            String escaped = str.replace("'", "\\'");
            escaped = escaped.replace("\\", "\\\\");
            return "'" + escaped + "'";
        } else if (obj instanceof Number) {
            // 数字类型（Integer、Double、Long 等）：直接转为字符串，不加引号
            return obj.toString();
        } else if (obj instanceof Boolean) {
            // 布尔类型：直接转为字符串（true/false），不加引号
            return obj.toString();
        } else if (obj.getClass().isArray()) {
            // 数组：转为 "[元素1, 元素2...]" 格式，不加单引号
            return Arrays.toString((Object[]) obj);
        } else {
            // 其他对象：默认调用 toString()，不加单引号（或根据需求序列化）
            return obj.toString();
        }
    }

    public Object getResult() {
        return resultStrategy.getData( this);
    }
}
